// MARK  薪资配置
const db = require('../../db')

// MARK  薪资数据

// MARK  POST / salarys / list	查询用户薪资列表
exports.getList = (req, res) => {
  const { page, pageSize, approvalsTypeChecks, approvalsStateChecks, departmentChecks } = req.body

  // 验证输入数据
  if (!page || !pageSize || page <= 0 || pageSize <= 0) {
    return res.status(400).json({ success: false, code: 10001, message: '页码和每页大小必须为正整数' })
  }

  // 构建查询条件
  let conditions = []
  let values = []

  if (approvalsTypeChecks && approvalsTypeChecks.length > 0) {
    conditions.push(`formOfEmployment IN (${approvalsTypeChecks.map(() => '?').join(', ')})`)
    values.push(...approvalsTypeChecks)
  }

  if (approvalsStateChecks && approvalsStateChecks.length > 0) {
    conditions.push(`inServiceStatus IN (${approvalsStateChecks.map(() => '?').join(', ')})`)
    values.push(...approvalsStateChecks)
  }

  if (departmentChecks && departmentChecks.length > 0) {
    conditions.push(`departmentId IN (${departmentChecks.map(() => '?').join(', ')})`)
    values.push(...departmentChecks)
  }

  // 构建查询语句
  const employeeQuery = `
    SELECT 
      id AS userId,
      formOfEmployment,
      inServiceStatus,
      mobile,
      timeOfEntry,
      username,
      workNumber,
      departmentId
    FROM employee
    ${conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''}
    LIMIT ? OFFSET ?
  `
  const offset = (page - 1) * pageSize
  values.push(pageSize, offset)

  // 执行查询
  db.query(employeeQuery, values, (err, employeeResults) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10002, message: '查询员工信息失败', error: err.message })
    }

    const userIds = employeeResults.map(employee => employee.userId)
    if (userIds.length === 0) {
      return res.json({
        success: true,
        code: 10000,
        data: {
          total: 0,
          rows: []
        },
        message: '执行成功'
      })
    }

    // 查询 total 记录数
    const totalQuery = `
      SELECT COUNT(*) AS total 
      FROM employee
      ${conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''}
    `
    db.query(totalQuery, values.slice(0, -2), (err, totalResult) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10002, message: '查询员工总数失败', error: err.message })
      }

      const total = totalResult[0].total

      // 查询 salary 表
      const salaryQuery = `
        SELECT 
          userId,
          currentBasicSalary,
          performance
        FROM salary
        WHERE userId IN (${userIds.map(() => '?').join(', ')})
      `
      db.query(salaryQuery, userIds, (err, salaryResults) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10002, message: '查询薪资信息失败', error: err.message })
        }

        const salaryMap = salaryResults.reduce((acc, salary) => {
          acc[salary.userId] = salary.currentBasicSalary
          return acc
        }, {})
        const performance = salaryResults.reduce((acc, salary) => {
          acc[salary.userId] = salary.performance
          return acc
        }, {})

        // 查询 department 表
        const departmentIds = Array.from(new Set(employeeResults.map(employee => employee.departmentId)))
        const departmentQuery = `
          SELECT 
            id,
            name AS departmentName
          FROM department
          WHERE id IN (${departmentIds.map(() => '?').join(', ')})
        `
        db.query(departmentQuery, departmentIds, (err, departmentResults) => {
          if (err) {
            return res.status(500).json({ success: false, code: 10002, message: '查询部门信息失败', error: err.message })
          }

          const departmentMap = departmentResults.reduce((acc, department) => {
            acc[department.id] = department.departmentName
            return acc
          }, {})

          // 处理结果
          const rows = employeeResults.map(employee => ({
            currentBasicSalary: salaryMap[employee.userId] || 0,
            performance: performance[employee.userId],
            departmentId: employee.departmentId,
            departmentName: departmentMap[employee.departmentId] || '',
            formOfEmployment: employee.formOfEmployment,
            id: employee.userId,
            inServiceStatus: employee.inServiceStatus,
            mobile: employee.mobile,
            timeOfEntry: employee.timeOfEntry,
            username: employee.username,
            workNumber: employee.workNumber
          }))

          // 返回数据
          res.json({
            success: true,
            code: 10000,
            data: {
              total,
              rows
            },
            message: '执行成功'
          })
        })
      })
    })
  })
}
// MARK  POST / salarys / modify / { userId }	员工调薪
exports.updateById = (req, res) => {
  const { id } = req.params
  const { performance, currentBasicSalary } = req.body

  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10022, message: '员工ID不能为空' })
  }
  if (performance === undefined || currentBasicSalary === undefined) {
    return res.status(400).json({ success: false, code: 10023, message: 'performance和currentBasicSalary不能为空' })
  }

  // 查询salary表中是否存在该userId的记录
  const selectQuery = 'SELECT * FROM salary WHERE userId = ?'
  db.query(selectQuery, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10024, message: '查询薪资信息失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10025, message: '薪资记录不存在' })
    }

    // 更新salary表中的记录
    const updateQuery = `
      UPDATE salary
      SET performance = ?, currentBasicSalary = ?
      WHERE userId = ?
    `
    db.query(updateQuery, [performance, currentBasicSalary, id], (err, updateResult) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10026, message: '更新薪资信息失败', error: err.message })
      }

      if (updateResult.affectedRows === 0) {
        return res.status(404).json({ success: false, code: 10027, message: '更新薪资记录失败' })
      }

      res.json({
        success: true,
        code: 10000,
        data: null,
        message: '更新薪资信息成功'
      })
    })
  })
}
